package com.design.classroommanagement.teacher

import com.alibaba.android.arouter.facade.annotation.Route
import com.design.classroommanagement.Pages
import com.design.classroommanagement.api.Role
import com.design.classroommanagement.api.User
import com.design.classroommanagement.api.getDao
import com.design.classroommanagement.databinding.ActivityTeacherPersonalBinding
import com.design.classroommanagement.manager.UserAccountManager
import com.laughing.lib.base.BaseFragmentNoVM
import com.laughing.lib.utils.arguments
import com.laughing.lib.utils.clickWithTrigger
import com.laughing.lib.utils.runInBg
import com.laughing.lib.utils.showToast

@Route(path = Pages.TeacherPersonalFragment)
class TeacherPersonalFragment : BaseFragmentNoVM<ActivityTeacherPersonalBinding>() {
    val userValue = arguments<User?>("user")
    val role = arguments<Role?>("role")
    var isAdd = false

    override fun initCompleted() {
        super.initCompleted()
        render()

    }

    fun render() {
        isAdd = userValue.value == null
        binding.apply {
            saveBtn.clickWithTrigger {
                save()
            }
            val user = userValue.value ?: return
            etAccount.setText(user.account)
            etPwd.setText(user.password)
            nameEt.setText(user.name)
            telEt.setText(user.telephone)
            collegeEt.setText(user.college)
            sexEt.setText(user.sex)
            ageEt.setText(user.age)

        }
    }

    fun save() {
        val user = userValue.value ?: User()
        binding.apply {
            user.account = etAccount.text.toString()
            user.password = etPwd.text.toString()
            user.name = nameEt.text.toString()
            user.telephone = telEt.text.toString()
            user.college = collegeEt.text.toString()
            user.age = ageEt.text.toString()
            user.sex = sexEt.text.toString()
        }

        if (user.account.isNullOrEmpty()) {
            showToast("请输入账号")
            return
        }

        if (user.password.isNullOrEmpty()) {
            showToast("请输入密码")
            return
        }

        runInBg {

            if (isAdd) {
                role.value?.getDao()?.add(user)
            } else {
                user.role.getDao().update(user)
            }
            finish()
        }
    }
}